package com.hs.jhzd.controller;

import java.util.List;
import java.util.Optional;

import com.hs.jhzd.entity.Dorm;
import com.hs.jhzd.repository.DormRepository;
import com.hs.jhzd.utils.ToolUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hs.jhzd.entity.DormArea;

@Controller
@RequestMapping("/dormArea")
public class DormAreaController {

  @Value("${jsbh}")
  private String jsbh;

  @Autowired
  private DormRepository repository;

  @RequestMapping("/findAll")
  @ResponseBody
  public List<DormArea> findAll() {
    return repository.findAllDormArea();
  }

  @RequestMapping("/save")
  @ResponseBody
  public void save(DormArea dormArea) {
    Dorm dorm = new Dorm();
    if(StringUtil.isBlank(dormArea.getId())){
      String oldId = repository.findZybh();
      dorm.setId(ToolUtils.CreatePrimaryKey(oldId));
      dorm.setDormcode(dormArea.getAreacode());
      dorm.setDormname(dormArea.getAreaname());
      dorm.setDormtype("11");
      repository.save(dorm);
    }else {
      repository.updateDormArea(dormArea.getAreacode(),dormArea.getAreaname(),dormArea.getId());
    }


  }

  @RequestMapping("/delete")
  @ResponseBody
  public void delete(String id) {
    repository.deleteById(id);
  }

  @RequestMapping("/findById")
  @ResponseBody
  public DormArea findById(String id) {
    Optional<DormArea> dormArea = repository.findByIdDormArea(id);
    return dormArea.isPresent() ? dormArea.get() : null;
  }

  @RequestMapping("/admin/main")
  public String mainPage(Model model) {
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("dormAreas", repository.findAllDormArea());
    return "dorm-area-list";
  }
}
